#include "chatdialog.h"
#include "ui_chatdialog.h"
#include <userinfo.h>
#include <client.h>
#include <QScrollBar>

extern userinfo user;
extern bool is_open_chatdialog;
extern userinfo otheruser;
extern QString serverIp;
extern int serverPort;
extern control cont;

chatdialog::chatdialog(int id, QString name):
    oid(id),
    oname(name),
    ui(new Ui::chatdialog)
{
    ui->setupUi(this);
    ui->label_title->setText(oname);
    ui->pushButton_backnow->setVisible(false);
    setWindowIcon(QIcon(":/res/comm2.png"));
    setWindowTitle("chat");
    is_open_chatdialog = true;
    tcpSocket = new QTcpSocket();
    timer = new QTimer();

    qDebug()<<oid<<oname;
//    connect(timer,SIGNAL(timeout()),this,SLOT(getchathistory()));
//    timer->start(500);
    getchathistory();

    connect(timer,SIGNAL(timeout()),this,SLOT(getnewmessage()));

    timer->start(500);

    connect(&cont, &control::allquit, [=](){
       close();
    });

}

chatdialog::~chatdialog()
{
    is_open_chatdialog = false;
    timer->stop();
    delete ui;
}

void chatdialog::on_pushButton_send_clicked()
{//发送消息
    if(ui->lineEdit_sendmessage->text()!="")
    {
        tcpSocket->abort();//取消已有链接
        tcpSocket->connectToHost(serverIp, serverPort);//链接服务器
        QString ip = tcpSocket->peerAddress().toString().section(":",3,3);
        int port = tcpSocket->peerPort();
        QString str = QString("[%1:%2]").arg(ip).arg(port);
        qDebug() << str ;
        if(!tcpSocket->waitForConnected(30000))
        {
            QMessageBox::warning(this, "Warning!", "网络错误", QMessageBox::Yes);
            this->close();
            user.islogin = false;
            client *cli = new client();
            cli->show();
        }
        else
        {//服务器连接成功
            //第一个是时间，第二个发送的ID，第三个是接受的ID，第四个是内容
            QString nowstr = QDateTime::currentDateTime().currentDateTime().toString("yyyy-MM-dd hh:mm:ss.zzz");
            QString message = QString("chat_send##%1##%2##%3##%4").arg(nowstr).arg(user.id).arg(oid).arg(ui->lineEdit_sendmessage->text());
            tcpSocket->write(message.toUtf8());
            tcpSocket->flush();
            ui->lineEdit_sendmessage->clear();
        }
    }
    else
    {//空消息
        QMessageBox::warning(this, "Warning!", "不能发送空消息", QMessageBox::Yes);
    }
}

void chatdialog::getnewmessage()
{
    qDebug() << "getnewmess" << endl;
    QTcpSocket* csock = new QTcpSocket(this);
    csock->connectToHost(serverIp, serverPort);//链接服务器

    if(!csock->waitForConnected(30000))
    {
        QMessageBox::warning(this, "Warning!", "网络错误", QMessageBox::Yes);
        this->close();
    }
    else
    {
        qDebug() << __LINE__ << ": running..." << endl;
        // 服务器连接成功
        QString request = QString("checkmessage##%1##%2##%3").arg(user.id).arg(oid).arg(totalCnt);
        csock->write(request.toUtf8());
        csock->flush();
        connect(csock,&QTcpSocket::readyRead,[=](){
            qDebug() << "正在尝试获取新消息..." << endl;
            QByteArray buffer = csock->readAll();
            if(QString(buffer).section("##",0,0)==QString("hasnewmessage"))
            {
                    // hasnewmessage##消息总条数##新消息条数##消息内容
                    totalCnt = QString(buffer).section("##", 1, 1).toInt();
                    int newmessCnt = QString(buffer).section("##", 2, 2).toInt();

                    QString chatshow = "";
                    for(int rownum = 0;rownum < newmessCnt ;rownum++)
                    {
                        QDateTime time = QDateTime::fromString( QString(buffer).section("##",rownum*3+3,rownum*3+3),"yyyy-MM-dd hh:mm:ss.zzz");
                        qDebug()<<time.toString();
                        QString timeshow = time.toString("MM-dd hh:mm:ss");
                        qDebug()<<timeshow;
                        QString idshow = "";
                        if(QString(buffer).section("##",rownum*3+4,rownum*3+4).toInt()==user.id)
                        {//我自己发送的消息
                            idshow = " 我：";
                        }
                        else
                        {
                            idshow =" "+ oname + "：";
                        }
                        chatshow = "("+timeshow+")" + idshow + QString(buffer).section("##",rownum*3+5,rownum*3+5) + chatshow;
                    }
                    if(nohaveMess)
                    {
                        nohaveMess = false;
                        ui->textBrowser_chat->clear();
                    }

                    ui->textBrowser_chat->append(chatshow);
            }

            else if(QString(buffer).section("##",0,0)==QString("nothasnewmessage"))
            {
                qDebug() << "没有新消息" << endl;
            }
        });
    }
}

void chatdialog::on_pushButton_clicked()
{
    qDebug()<<is_open_chatdialog;

    is_open_chatdialog = false;
    qDebug()<<is_open_chatdialog;
    this->close();
    timer->stop();
}

void chatdialog::getchathistory()
{
    tcpSocket->abort();//取消已有链接
    tcpSocket->connectToHost(serverIp, serverPort);//链接服务器

    if(!tcpSocket->waitForConnected(30000))
    {
        QMessageBox::warning(this, "Warning!", "网络错误", QMessageBox::Yes);
        this->close();
    }
    else
    {
        //服务器连接成功
        QString message = QString("chat_history##%1##%2").arg(user.id).arg(oid);
        tcpSocket->write(message.toUtf8());
        tcpSocket->flush();
        connect(tcpSocket,&QTcpSocket::readyRead,[=](){
            QByteArray buffer = tcpSocket->readAll();
            if(QString(buffer).section("##",0,0)==QString("chat_history_ok"))
            {
                // chat_history_ok##总消息条数##显示消息条数##消息内容
                    totalCnt = QString(buffer).section("##", 1, 1).toInt();
                    qDebug() << "总消息数：" << totalCnt << endl;
                    QString chatshow = "";
                    int cnt = QString(buffer).section("##", 2, 2).toInt(); // 显示消息条数
                    for(int rownum = 0;rownum < cnt ;rownum++)
                    {
                        QDateTime time = QDateTime::fromString( QString(buffer).section("##",rownum*3+3,rownum*3+3),"yyyy-MM-dd hh:mm:ss.zzz");
                        qDebug()<<time.toString();
                        QString timeshow = time.toString("MM-dd hh:mm:ss");
                        qDebug()<<timeshow;
                        QString idshow = "";
                        if(QString(buffer).section("##",rownum*3+4,rownum*3+4).toInt()==user.id)
                        {//我自己发送的消息
                            idshow = " 我：";
                        }
                        else
                        {
                            idshow =" "+ oname + "：";
                        }
                        chatshow = "("+timeshow+")" + idshow + QString(buffer).section("##",rownum*3+5,rownum*3+5) +"\n" + chatshow;
                    }
                    ui->textBrowser_chat->setText(chatshow);
            }
            else if(QString(buffer).section("##",0,0)==QString("chat_history_error"))
            {
                ui->textBrowser_chat->setText("无消息记录");
                nohaveMess = true;
            }
        });
    }
}

void chatdialog::closeEvent(QCloseEvent *event)
{
    is_open_chatdialog = false;
    timer->stop();
}



void chatdialog::on_pushButton_ago_clicked()
{
    QTcpSocket* agoSock = new QTcpSocket(this);
    agoSock->abort();//取消已有链接
    agoSock->connectToHost(serverIp, serverPort);//链接服务器

    if(!agoSock->waitForConnected(30000))
    {
        QMessageBox::warning(this, "Warning!", "网络错误", QMessageBox::Yes);
        this->close();
    }
    else
    {
        //服务器连接成功

        ui->pushButton_send->setVisible(false);
        ui->lineEdit_sendmessage->setVisible(false);
        ui->textBrowser_chat->clear();
        ui->pushButton_ago->setVisible(false);
        ui->pushButton_backnow->setVisible(true);
        ui->textBrowser_chat->setFixedSize(331, 421);

        QString request = QString("getallchathistory##%1##%2").arg(user.id).arg(oid);
        agoSock->write(request.toUtf8());
        agoSock->flush();
        connect(agoSock,&QTcpSocket::readyRead,[=](){
            QByteArray buffer = agoSock->readAll();
            qDebug() << "buff = " << buffer << endl;
            if(QString(buffer).section("##",0,0)==QString("getallchathistory_ok"))
            {
                // getallchathistory_ok##总消息条数##显示消息条数##消息内容
                    totalCnt = QString(buffer).section("##", 1, 1).toInt();
                    qDebug() << "总消息数：" << totalCnt << endl;
                    QString chatshow = "";
                    int cnt = QString(buffer).section("##", 2, 2).toInt(); // 显示消息条数
                    for(int rownum = 0;rownum < cnt ;rownum++)
                    {
                        QDateTime time = QDateTime::fromString( QString(buffer).section("##",rownum*3+3,rownum*3+3),"yyyy-MM-dd hh:mm:ss.zzz");
                        qDebug()<<time.toString();
                        QString timeshow = time.toString("MM-dd hh:mm:ss");
                        qDebug()<<timeshow;
                        QString idshow = "";
                        if(QString(buffer).section("##",rownum*3+4,rownum*3+4).toInt()==user.id)
                        {
                            // 我自己发送的消息
                            idshow = " 我：";
                        }
                        else
                        {
                            idshow =" "+ oname + "：";
                        }
                        chatshow = "("+timeshow+")" + idshow + QString(buffer).section("##",rownum*3+5,rownum*3+5) +"\n" + chatshow;
                    }
                    ui->textBrowser_chat->setText(chatshow);
            }
            else if(QString(buffer).section("##",0,0)==QString("getallchathistory_error"))
            {
                ui->textBrowser_chat->setText("无消息记录");
            }
        });
    }
}

void chatdialog::on_pushButton_backnow_clicked()
{
    ui->textBrowser_chat->setFixedSize(331, 351);
    ui->pushButton_backnow->setVisible(false);
    ui->pushButton_ago->setVisible(true);
    ui->pushButton_send->setVisible(true);
    ui->lineEdit_sendmessage->setVisible(true);
    ui->textBrowser_chat->clear();
    getchathistory();
}
